'''
Created on 18/06/2012

@author: mekoda
'''

from main.process import ProcessStates
import functools

def getMostPrioritary(oneProcess,anotherProcess):
    if(oneProcess.pcb.priority<anotherProcess.pcb.priority):
        return oneProcess
    else:
        return anotherProcess
    
def sortAndTakeThemostPrioritary(self):
    candidate = functools.reduce(getMostPrioritary,self.processes)
    self.processes.remove(candidate)
    return candidate     #HAY QUE TESTEAR SI TODO ESTO ES ATOMICO

#-----------------#

def getProcessLength(aProcess):
    result = 0
    for inst in aProcess.instructions:
        result = result + inst.timeRemaining
    return result
    

def getShortest(oneProcess,anotherProcess):
    if(getProcessLength(oneProcess)<getProcessLength(anotherProcess)):
        return oneProcess
    else:
        return anotherProcess

def sortAndTakeTheShortest(self):
    candidate = functools.reduce(getShortest,self.processes.processes)
    self.processes.cut(candidate)
    return candidate     #HAY QUE TESTEAR SI TODO ESTO ES ATOMICO

def sortAndReturnTheShortest(self):
    candidate = functools.reduce(getShortest,self.processes.processes)
    return candidate    
    
#-----------------#

def updatePCB(aProcess):
    #Get the last item index
    lastIndex = len(aProcess.instructions)-1
    #If Im executing the last instruction...
    if((aProcess.instructions[lastIndex])== aProcess.pcb.currentInstruction):
        #then set the Process status as Terminated
        aProcess.pcb.status = ProcessStates.FINISHED
        aProcess.pcb.currentInstruction = None
    else:
        # Update the current Instruction (+1)
        nextInstruction(aProcess)
        aProcess.pcb.status = ProcessStates.READY

        
def nextInstruction(aProcess):
    ci = aProcess.pcb.currentInstruction
    indexNi = (aProcess.instructions.index(ci))+1
    ni = aProcess.instructions[indexNi]
    aProcess.pcb.currentInstruction = ni
    

#------MEMORY COOL STUFF-------------------#
def defineProcessFrames(aProcess, theFrameSize):
    pass

def framerizeAddedInstruction(aProcess):
    pass
    
    